<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/about' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card style="margin-top: 20px">
      <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="add" plain>添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一层循环 -->
            <div class="expand_box">
              <el-row
                v-for="(item1, index1) in scope.row.children"
                :key="item1.id"
                :class="[
                  'border_bottom',
                  index1 == 0 ? 'border_top' : '',
                  'vcenter',
                ]"
              >
                <el-col :span="8">
                  <el-tag @close="closeTag(scope.row, item1.id)" closable>{{
                    item1.authName
                  }}</el-tag>
                </el-col>

                <!-- 二层循环 -->
                <el-col :span="16">
                  <el-row
                    v-for="(item2, index2) in item1.children"
                    :class="[index2 == 0 ? '' : 'border_top', 'vcenter']"
                    :key="item2.id"
                  >
                    <el-col :span="8">
                      <el-tag
                        type="success"
                        @close="closeTag(scope.row, item2.id)"
                        closable
                        >{{ item2.authName }}</el-tag
                      >
                    </el-col>
                    <!-- 三层循环 -->
                    <el-col :span="16">
                      <el-tag
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        @close="closeTag(scope.row, item3.id)"
                        type="warning"
                        closable
                        >{{ item3.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="180"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="180">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="180">
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              @click="showRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加的弹框 -->
    <el-dialog title="添加角色" :visible.sync="dialogFormVisible">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>

        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 编辑弹框 -->
    <el-dialog title="编辑角色" :visible.sync="dialogFormVisible1">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="edit">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 权限弹框 -->
    <el-dialog title="分配权限" :visible.sync="dialogFormVisible3">
      <el-tree
        :data="rightList"
        show-checkbox
        ref="treeRef"
        @check-change="handleCheckChange"
        default-expanded-all
        node-key="id"   
        :default-checked-keys="checkedKeys"
        :props="treeProps"
      >
      </el-tree>   

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="setRole"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name:"roles",
  data() {
    return {
      // 权限列表模态框关闭
      dialogFormVisible3: false,
      checkedKeys: [],
      // 权限列表

      rightList: [],
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 表格渲染
      tableData: [],
      //    添加的数据
      ruleForm: {
        roleName: "",
        roleDesc: "",
      },
      //   添加数据的验证
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      //   添加的模态框关闭
      dialogFormVisible: false,
      //   编辑的模态框关闭
      dialogFormVisible1: false,
    };
  },
  mounted() {
    this.getdata();
  },
  methods: {
    // 为角色分配权限
    async setRole(){
      let arr=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      let rids=arr.join(",")
      let {data:res}=await this.$axios({
        url:`api/private/v1/roles/${this.roleId}/rights`,
        method:"Post",
        data:{
          roleId:this.roleId,
          rids
        }
      }).catch(err=>err)
      if(res.meta.status!==200 ) return $message.error("更新角色的权限失败")
      this.$message.success("成功更新权限")
      this.dialogFormVisible3=false
      this.getdata()
    }, 

    // 选择性权限
    handleCheckChange() {},
    // 分配权限相关
    async showRightDialog(role) {
      // console.log(role,'sd');
      this.roleId=role.id;
      this.getKeys(role, this.checkedKeys);
      let { data: res } = await this.$axios({
        url: `api/private/v1/rights/tree`,
      }).catch((err) => err);
      if (res.meta.status !== 200)
        return this.$message.error("权限列表获取错误");
      this.rightList = res.data;
      this.dialogFormVisible3 = true;
    },
    getKeys(role, arr) {
      if (!role.children) {
        return arr.push(role.id);
      }
      role.children.forEach((item) => {
        this.getKeys(item, arr);
      });
    },  
    // 移除权限
    async closeTag(role, rightId) {
      let result = await this.$confirm("您确认要移出权限嘛?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).catch((err) => err);
      if (result === "confirm") {
        // 移出权限
        let { data: res } = await this.$axios({
          url: `api/private/v1/roles/${role.id}/rights/${rightId}`,
          method: "delete",
        }).catch((err) => err);
        if (res.meta.status !== 200) return this.$message.error("权限取消失败");
        role.children = res.data;
      }
    },
    //编辑
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogFormVisible1 = true;
      this.ruleForm = row;
    },
    // 编辑请求接口
    async edit() {
      let result = await this.$axios({
        url: `api/private/v1/roles/${this.ruleForm.id}`,
        method: "PUT",
        data: this.ruleForm,
      });
      console.log(result);
      if (result.data.meta.status != 200)
        return this.$message.error(result.data.meta.msg); 
      this.dialogFormVisible1 = false;
      this.$message.success(result.data.meta.msg);
    },
    //  删除 的请求接口
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          var res = await this.$axios({
            url: `/api/private/v1/roles/${row.id}`,
            method: "delete",
          });
          console.log(res, "删除角色");
          this.getdata();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 添加 请求接口
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          var res = await this.$axios({
            url: "/api/private/v1/roles",
            method: "post",
            data: this.ruleForm,
          });
          console.log(res, "添加角色");
          this.getdata();
          this.dialogFormVisible = false;
          this.ruleForm = {};
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 添加打开模态框
    add() {
      this.dialogFormVisible = true;
    },
    // 渲染
    async getdata() {
      var res = await this.$axios({
        url: "/api/private/v1/roles",
        method: "get",
      });
      console.log(res.data.data, "角色列表");
      this.tableData = res.data.data;
    },
  },
};
</script>

<style lang="scss" scoped>
.expand_box {
  width: 90%;
  margin: 0 auto;
}
.border_bottom {
  border-bottom: 1px solid #ebeef5;
}
.border_top {
  border-top: 1px solid #ebeef5;
}
.vcenter {
  display: flex;
  align-items: center;
}
.el-tag {
  margin: 7px;
}
</style>